import { defineStore } from 'pinia'
import { getCartInfo, recommendlist, removeCart, updatenumCart,selectoneCart,checkCartAll,addOrderCart } from '@/api/cart'
export const useCartStore = defineStore('useCartStore', {
  state() {
    return {
      datail: [],
      recommendlist: []
    }
  },
  //   请求
  actions: {
    //获取购物车详情
    async getDetailInfoHandler(userid: string) {
      const result = await getCartInfo(userid)
      if ((result as any).code == 200) {
        this.datail = result.data
      } else {
        this.datail = []
      }
    },
    //获取推荐商品
    async recommendlistHandler(params: { count: number, limitNum: number }) {
      const result = await recommendlist(params)

      if ((result as any).code == 200) {
        //如果服务器没有数据了,获取的数据的长度的是<=0,告诉组件,服务器没有数据
        if (result.data.length <= 0) {
          //返回一个失败的promise
          return Promise.reject("没了")
        } else {
          if (params.count == 1) {
            this.recommendlist = result.data;
          } else {
            this.recommendlist = this.recommendlist.concat(result.data)
          }
        }
      }
    },
    //删除购物车一条数据
    async removeCartHandler(cartid: string) {
      await removeCart(cartid)
    },
    //商品数量++
    async updatenumCartHandler(data:{cartid: string,num: number }) {
      await updatenumCart(data)
    },
    //当前商品选中状态
    async selectoneCartHandler(data:{cartid: string,flag: boolean}) {
      await selectoneCart(data)
    },
     //批量修改购物车里面的选中状态
     async checkCartAllHandler(data:{userid:string,type:boolean}) {
      await checkCartAll(data)
    },

    //  添加订单
    async addOrderCartHandler(userid:string) {
      const result= await addOrderCart(userid)
      if((result as any).code == 200){
        // 把服务器返回的时间戳带回去用来区分页面
        return Promise.resolve((result as any).time)
     }
    },
  },
  //  计算属性
  getters: {

  }

})
